//
//  CreditCardsController.m
//  SmartCheckout
//
//  Created by Barak Edry on 12/31/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "CreditCardsController.h"
#import <QuartzCore/QuartzCore.h>


@implementation CreditCardsController
@synthesize scrollView;
@synthesize pageControl;
@synthesize cards;
@synthesize cardViews;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{

    newCardIndex = -1;
    
    currentEditingCardView = nil;
    currentBackView = nil;

    //self.cards = [[NSMutableArray alloc] init];
    numberOfCards = [self.cards count];

    // view controllers are created lazily
    // in the meantime, load the array with placeholders which will be replaced on demand
    cardViews = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < numberOfCards; i++)
    {
		[cardViews addObject:[NSNull null]];
    }
    
    
    // a page is the width of the scroll view
    scrollView.pagingEnabled = YES;
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * numberOfCards, scrollView.frame.size.height);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    scrollView.delegate = self;
    
    pageControl.numberOfPages = numberOfCards;
    pageControl.currentPage = 0;
    
    // pages are created on demand
    // load the visible page
    // load the page on either side to avoid flashes when the user starts scrolling
    //
    [self loadScrollViewWithCardIndex:0];
    [self loadScrollViewWithCardIndex:1];
    
    _budgetUtilizationBar = [[SectionsUtilizationBar alloc] init];
    _budgetUtilizationBar.frame = CGRectMake(30, 310, 260, 30);
    _budgetUtilizationBar.animationTime = 0.5;
    [self.view addSubview:_budgetUtilizationBar];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{

    for (UIView* cardView in cardViews) {
        [cardView removeFromSuperview];
    }
    [cardViews removeAllObjects];
    
    currentEditingCardView = nil;
    currentBackView = nil;
    [self setScrollView:nil];
    [self setPageControl:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



- (void)loadScrollViewWithCardIndex:(int)cardIndex
{
    
    if (cardIndex < 0)
        return;
    if (cardIndex >= numberOfCards)
        return;
    
    // replace the placeholder if necessary
    CardView *cardView = [cardViews objectAtIndex:cardIndex];
    if ((NSNull *)cardView == [NSNull null])
    {
        cardView = [CardView cardViewWithCard:[cards objectAtIndex:cardIndex]];
        [cardViews replaceObjectAtIndex:cardIndex withObject:cardView];
    }
    
    CGFloat paddingFromLeft = 20;
    // add the controller's view to the scroll view
    if (![cardView.superview isEqual:scrollView])
    {
        CGRect frame = cardView.frame;
        frame.origin.x = (scrollView.frame.size.width * cardIndex) + paddingFromLeft;
        frame.origin.y = 8;
        cardView.frame = frame;

        [scrollView addSubview:cardView];
        
        if (cardIndex == newCardIndex) {
            cardView.layer.transform = CATransform3DMakeScale(0.1, 0.1, 0.1);                      
        }
        
        [cardView updateReflection];
        
    }
    
    [self displaySummery];
   
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    // We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
    // which a scroll event generated from the user hitting the page control triggers updates from
    // the delegate method. We use a boolean to disable the delegate logic when the page control is used.
    if (pageControlUsed)
    {
        // do nothing - the scroll was initiated from the page control, not the user dragging
        return;
    }
	
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    [self loadScrollViewWithCardIndex:page - 1];
    [self loadScrollViewWithCardIndex:page];
    [self loadScrollViewWithCardIndex:page + 1];
    
    // A possible optimization would be to unload the views+controllers which are no longer visible
}

- (IBAction)showCardInfo:(id)sender {
    int cardIndex = pageControl.currentPage;
    CardView *cardView = [cardViews objectAtIndex:cardIndex];
    currentEditingCardView = cardView;

    if (cardView != nil) {
        // load and show back of the card
        
        currentBackView = [CardBackView backViewWithCard:[cards objectAtIndex:cardIndex]];
        currentBackView.frame = cardView.frame;
        currentBackView.deleage = self;

        [scrollView setScrollEnabled:NO];
         
        currentEditingCardView = cardView;
        [UIView transitionWithView:scrollView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [cardView removeFromSuperview];
            [scrollView addSubview:currentBackView];
        } completion:^(BOOL finished) {
            [currentBackView.nameInput becomeFirstResponder];
        }];
        
    }
    
}




- (void) cardDidSaved:(Card *)card{

    
}

// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{

    pageControlUsed = NO;
}

- (void)showCardInfoButton
{

    [UIView animateWithDuration:0.75 delay:0.4 options:UIViewAnimationOptionAllowUserInteraction animations:^{

    } completion:NULL];
}

// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    [self showCardInfoButton];

    pageControlUsed = NO;
    
}

- (IBAction)changePage:(id)sender
{
    int page = pageControl.currentPage;
	[self changeToPageIndex:page];

}

- (void)changeToPageIndex:(int)pageIndex {
    // load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
    
    
    [self loadScrollViewWithCardIndex:pageIndex - 1];
    [self loadScrollViewWithCardIndex:pageIndex];
    [self loadScrollViewWithCardIndex:pageIndex + 1];
    
	// update the scroll view to the appropriate page
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * pageIndex;
    frame.origin.y = 0;
    [scrollView scrollRectToVisible:frame animated:YES];
    
	// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
    pageControlUsed = YES;

    if (pageIndex == newCardIndex) {

        CardView* cardView = [cardViews objectAtIndex:pageIndex];
        [UIView animateWithDuration:0.5 delay:0.5 options:UIViewAnimationCurveEaseIn animations:^{
            cardView.layer.transform = CATransform3DMakeScale(1, 1, 1);
        } completion:^(BOOL finished) {
            [self performSelector:@selector(showCardInfo:) withObject:nil afterDelay:0.25];
        }];
        
        newCardIndex = -1;
    } else {
        [self performSelector:@selector(showCardInfoButton) withObject:nil afterDelay:0.25];        
    }
    
}


- (void) displaySummery {
    NSMutableArray* values = [[NSMutableArray alloc] init];
    
    [NSNumber numberWithInt:rand() % 100];
    srand(time(NULL));
    
    for (int i=0; i < 6; i++) {
        [values addObject:[NSNumber numberWithInt:rand() % 100]];
    }
    _budgetUtilizationBar.total = 500;
    
    //_budgetUtilizationBar.sectionsValues = @[@23, @14, @8, @11, @31];
    _budgetUtilizationBar.sectionsValues = values;
    [_budgetUtilizationBar update];

}


- (void) cardEditingDidFinish {

    newCardIndex = -1;
    CardView* cardView = currentEditingCardView;
    if (cardView != nil) {
        // load and show back of the card
        CardBackView* backView = currentBackView;
        

    }
    
}


@end
